package com.example.mfbq.activities;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.mfbq.adapter.DataAdapter;
import com.example.mfbq.adapter.DataQueueAdapter;
import com.example.mfbq.R;
import com.example.mfbq.arithmetic.FCFSArithmetic;
import com.example.mfbq.arithmetic.HRRNArithmetic;
import com.example.mfbq.arithmetic.MFBQArithmetic;
import com.example.mfbq.arithmetic.Process;
import com.example.mfbq.arithmetic.RRArithmetic;
import com.example.mfbq.arithmetic.SJFArithmetic;
import com.example.mfbq.handler.ArithmeticHandler;

import java.util.ArrayList;
import java.util.List;

public class ShowActivity extends AppCompatActivity {

    private int queueNum;
    private int queueTime;
    private int time;
    private String arithmetic;
    private List processes;
    private boolean sjfFight;
    private DataAdapter dataAdapter;

    private RecyclerView recyclerView;
    private LinearLayout linearLayout;
    private Button startBtn;

    private Process[] pro;
    private boolean fight;
    private ArithmeticHandler AHandler;
    private ListView infoTipLv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);

        Display defaultDisplay = getWindowManager().getDefaultDisplay();
        Point point = new Point();
        defaultDisplay.getSize(point);
        int screenHeight = point.y - getSupportActionBar().getHeight();

        Configuration config = ShowActivity.this.getResources().getConfiguration();
        if(config.orientation == Configuration.ORIENTATION_PORTRAIT){
            ShowActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }else{
            Intent intent = getIntent();
            Bundle data = intent.getExtras();
            fight = data.getBoolean("fight");
            sjfFight = data.getBoolean("sjfFight");
            queueNum = data.getInt("queueNum");
            queueTime = data.getInt("queueTime");
            time = data.getInt("time");
            arithmetic = data.getString("arithmetic");
            String listJson = data.getString("pro");
            processes = (List)JSON.parse(listJson);

            int arrayLength = processes.size();
            pro = new Process[arrayLength];
            for(int i=0;i<arrayLength;i++){
                JSONObject jsonObject = (JSONObject)(processes.get(i));
                int processId = (int)(jsonObject.get("processId"));
                int comeTime = (int)(jsonObject.get("comeTime"));
                int serveTime = (int)(jsonObject.get("serveTime"));
                Process p = new Process(processId, comeTime, serveTime);
                pro[i] = p;
            }

            if(arithmetic.equals("mfbq")){
                if(fight){
                    getSupportActionBar().setTitle("抢占式多级反馈队列算法");
                }else{
                    getSupportActionBar().setTitle("非抢占式多级反馈队列算法");
                }
            }else if(arithmetic.equals("fcfs")){
                getSupportActionBar().setTitle("先来先服务算法");
            }else if(arithmetic.equals("sjf")){
                if(sjfFight){
                    getSupportActionBar().setTitle("抢占式短进程优先算法");
                }else{
                    getSupportActionBar().setTitle("非抢占式短进程优先算法");
                }
            }else if(arithmetic.equals("hrrn")){
                getSupportActionBar().setTitle("高响应比优先算法");
            }else if(arithmetic.equals("rr")){
                getSupportActionBar().setTitle("时间片轮转算法");
            }else{
                Toast.makeText(ShowActivity.this, "不知道选择的是什么算法", Toast.LENGTH_SHORT).show();
            }

            recyclerView = this.findViewById(R.id.recycler);
            recyclerView.setHasFixedSize(true);
            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            layoutManager.setSmoothScrollbarEnabled(true);
            recyclerView.setLayoutManager(layoutManager);
            List<Integer> ls = new ArrayList<>();
            dataAdapter = new DataAdapter(ls, pro);
            recyclerView.setAdapter(dataAdapter);
            DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
            defaultItemAnimator.setAddDuration(1000);
            recyclerView.setItemAnimator(defaultItemAnimator);

            linearLayout = this.findViewById(R.id.queue_area);
            for(int j=0;j<queueNum;j++){
                View view = getLayoutInflater().inflate(R.layout.queue_item, null);

                TextView textView = view.findViewById(R.id.queue_id);
                textView.setText("队列"+j);

                RecyclerView listView = view.findViewById(R.id.ready_queue);
                DataQueueAdapter dAdapter = new DataQueueAdapter(new ArrayList<Integer>());
                LinearLayoutManager llm = new LinearLayoutManager(this);
                llm.setOrientation(LinearLayoutManager.VERTICAL);
                llm.setSmoothScrollbarEnabled(true);
                listView.setLayoutManager(llm);
                listView.setBackgroundColor(Color.WHITE);
                listView.setAdapter(dAdapter);
                listView.setMinimumHeight(screenHeight - dip2px(this, 100));
                DefaultItemAnimator dia = new DefaultItemAnimator();
                dia.setAddDuration(1000);
                dia.setRemoveDuration(1000);
                listView.setItemAnimator(dia);

                linearLayout.addView(view);
            }

            infoTipLv = this.findViewById(R.id.info_tip);
            BaseAdapter baseAdapter = new BaseAdapter() {
                @Override
                public int getCount() {
                    return 0;
                }

                @Override
                public Object getItem(int position) {
                    return null;
                }

                @Override
                public long getItemId(int position) {
                    return 0;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    return null;
                }
            };
            infoTipLv.setAdapter(baseAdapter);

            AHandler = new ArithmeticHandler(this, recyclerView, linearLayout, infoTipLv);

            startBtn = this.findViewById(R.id.start_ui);
            startBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dataAdapter.clear();
                    if(arithmetic.equals("mfbq")){
                        MFBQArithmetic mfbq = new MFBQArithmetic(pro, queueNum, queueTime, AHandler);
                        if(fight){
                            mfbq.startFighting();
                        }else{
                            mfbq.start();
                        }
                    }else if(arithmetic.equals("fcfs")){
                        FCFSArithmetic fcfsArithmetic = new FCFSArithmetic(pro, AHandler);
                        fcfsArithmetic.start();
                    }else if(arithmetic.equals("sjf")){
                        SJFArithmetic sjfArithmetic = new SJFArithmetic(pro, AHandler);
                        if(sjfFight){
                            sjfArithmetic.startFight();
                        }else{
                            sjfArithmetic.start();
                        }
                    }else if(arithmetic.equals("hrrn")){
                        HRRNArithmetic hrrnArithmetic = new HRRNArithmetic(pro, AHandler);
                        hrrnArithmetic.start();
                    }else if(arithmetic.equals("rr")){
                        RRArithmetic rrArithmetic = new RRArithmetic(pro, time, AHandler);
                        rrArithmetic.start();
                    }else{
                        Toast.makeText(ShowActivity.this, "不知道选择的是什么算法", Toast.LENGTH_SHORT).show();
                    }

                    v.setVisibility(View.GONE);
                }
            });
        }
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}